import { ISendMailOptions, MailerService } from '@nestjs-modules/mailer';
import { HttpException, Injectable } from '@nestjs/common';
import dayjs = require('dayjs');
import Chalk = require('chalk');
const Log = console.log;

@Injectable()
export class EmailService {
  constructor(private readonly mailerService: MailerService) {}

  /**
   * 发送邮件验证码
   * @param data 邮件主体信息
   */
  async sendEmailCode(data: { email: string; subject: string; sign?: string }) {
    try {
      const code = Math.random().toString().slice(-6);
      const date = dayjs().format('YYYY-MM-DD HH:mm:ss');
      const sendMailOptions: ISendMailOptions = {
        to: data.email,
        subject: data.subject || '用户邮箱验证',
        // html: `<div>
        //   <h1>标题</h1>
        //   内容${data.sign}
        // </div>`,
        template: process.cwd() + '/template/email',
        //内容部分都是自定义的
        context: {
          code, //验证码
          date, //日期
          sign: data.sign || '系统邮件,回复无效。', //发送的签名,当然也可以不要
        },
      };
      await this.mailerService.sendMail(sendMailOptions);
      return { message: '发送成功' };
    } catch (error) {
      Log(Chalk.red(`发送邮件出错：${error}`));
      throw new HttpException(`发送邮件出错：${error}`, 401);
      // return { error };
    }
  }
}
